package uvsq.acsis.projects.xml.parsers;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.log4j.Logger;

public class XSLTProcessor {

	private static final Logger log = Logger.getLogger(XSLTProcessor.class);
	
	public static String process(String webSUrl, String trsfmString){
		
		Transformer transformer = null;
		TransformerFactory factory = null;
		
		try {
			
			StringWriter sr = new StringWriter();
			
			factory = TransformerFactory.newInstance();
		
			transformer = factory.newTransformer(new StreamSource(new File(trsfmString)));
			
			BufferedReader rd = new BufferedReader(new StringReader(getHttpStreamAsString(webSUrl)));
			
			Source src = new StreamSource(rd);
			transformer.transform(src, new StreamResult(sr));	
			
			return sr.toString();
			
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static String getHttpStreamAsString(String webSUrl){
		
		URL url = null;
		URLConnection uc = null;
		StringBuilder sb = new StringBuilder();
		
		try {
			
			url = new URL(webSUrl);
			uc = url.openConnection();
			InputStream is = uc.getInputStream();
			
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			
			String str;
			while ((str = rd.readLine()) != null) {
				sb.append(str);
			    log.debug(str);
			}
			rd.close();
			
			return sb.toString();
		} 
		catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
}
